<template>
  <el-button :type="type" :text="props.isText" @click="openLoginDialog=true">{{ props.text }}</el-button>
  <el-dialog append-to-body v-model="openLoginDialog" width="800">
    <avue-login v-model="form"
                :option="loginFormOption"
                @refresh="refresh"
                :codesrc="codeSrc"
                @submit="handleLogin">
    </avue-login>
  </el-dialog>
</template>
<script setup>
import {ref} from 'vue';
import router from "@/router/index.js";
import {authLogin} from "@/views/auth/js/AuthRequest.js";
import {loginFormOption} from "@/views/auth/js/AuthOption.js";
import {useUserStore} from "@/store/index.js";

import {ElMessage} from "element-plus";
import {photoCaptcha} from "@/views/auth/js/CommonRequest.js";

const form = ref({});
const userStore = useUserStore();
const codeSrc = ref('');
const orgCaptcha = ref('')
const handleLogin = (form) => {
  form.orgCaptcha = orgCaptcha.value
  authLogin(form).then(res => {
    if (res.success) {
      userStore.setLoginUserInfo(res.data)
      router.replace("/")
      openLoginDialog.value = false
    } else {
      ElMessage.error('账号或密码错误')
      refresh()
    }
  })
};

const refresh = () => {
  photoCaptcha().then(res => {
    if (res.success) {
      codeSrc.value = `data:image/jpeg;base64,${res.data.key}`;
      orgCaptcha.value = res.data.value
    }
  })
}

// 页面加载时自动获取验证码
refresh();
const props = defineProps({
  text: {
    type: String,
    default: "登录/注册"
  },
  type: {
    type: String,
    default: "primary"
  },
  isText: {
    type: Boolean,
    default: false
  }
})

const openLoginDialog = ref(false);

</script>
<style scoped>

</style>